package org.nestor.demo.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.nestor.demo.protobuf.Buyer;
import org.nestor.demo.protobuf.Order;
import org.nestor.demo.protobuf.OrderQueryGrpc;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;

/**
 * @author : Nestor.Bian
 * @version : V 1.0
 * @date : 2025/3/6
 */
public class OrderGRPCClient {
    private static final String host = "localhost";
    private static final int serverPort = 9999;

    public static void main(String[] args) {
        //1,拿到一个通信channel
        ManagedChannel channel = ManagedChannelBuilder.forAddress(host, serverPort).
                usePlaintext()// 这里将使用纯文本，无需任何加密
                .build();

        try {
            //2.拿到stub对象
            OrderQueryGrpc.OrderQueryBlockingStub orderQueryBlockingStub = OrderQueryGrpc.newBlockingStub(channel);
            // gRPC的请求参数
            Buyer buyer = Buyer.newBuilder().setBuyerId(101).build();

            // 通过stub发起远程gRPC请求
            // gRPC的响应
            Iterator<Order> orderIterator = orderQueryBlockingStub.listOrders(buyer);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            while (orderIterator.hasNext()) {
                Order order = orderIterator.next();
                System.out.println("订单ID：" + order.getOrderId() + "产品ID：" + order.getProductId() + "日期：" +
                        // 使用DateTimeFormatter将时间戳转为字符串
                        dtf.format(LocalDateTime.ofEpochSecond(order.getOrderTime(), 0, ZoneOffset.of("+8"))) + "备注：" + order.getBuyerRemark());
            }
        } finally {
            // 5.关闭channel, 释放资源.
            channel.shutdown();
        }

    }

}
